namespace SampleMiddleware;

public static class MiddlewareExtension
{
    /// <summary>
    /// 中断拦截器
    /// </summary>
    /// <param name="applicationBuild"></param>
    /// <param name="func"></param>
    public static void Run(this ApplicationBuild applicationBuild, Func<HttpSampleContext, Task> func)
    {
        applicationBuild.Use((next) => { return context => func(context); });
    }

    /// <summary>
    /// 另外起一个分支
    /// </summary>
    /// <param name="applicationBuild"></param>
    /// <param name="path">请求地址</param>
    /// <param name="action">新链路</param>
    public static void Map(this ApplicationBuild applicationBuild, string path, Action<ApplicationBuild> action)
    {
        //从原始对象创建一个新的
        var newApplicationBuild = applicationBuild.New();
        action.Invoke(newApplicationBuild);
        //切断分支
        var branch = newApplicationBuild.Build();
        applicationBuild.Use(next =>
        {
            return context =>
            {
                //检验地址
                if (context.Path.StartsWith(path))
                {
                    branch(context);
                }
                else
                    next(context);

                return Task.CompletedTask;
            };
        });
    }
}